import os
import cv2
from tqdm import tqdm
import argparse

# 参数
folder_path = '../images'   # 指定要读取的文件夹路径
save_path = '../video'      # 制定要保存的文件夹路径
save_name = 'video'
image_second = 5.



# 读取文件夹里的所有照片
def read_images_name(file_location):
    # 使用os模块的listdir函数读取文件夹中所有文件名
    file_names = os.listdir(file_location)
    # 使用列表推导式过滤掉文件夹中的子文件夹，只保留文件名
    file_names = [file_name for file_name in file_names if os.path.isfile(os.path.join(folder_path, file_name))]
    file_names.sort()
    return file_names


# 根据list读取所有图像
def read_images(file_location, image_names):
    images_list = []
    for image_name in image_names:
        image = cv2.imread(file_location + "/" + image_name)
        images_list.append(image)
    return images_list




# 合成视频 参数： 保存路径  图像列表 每张图像的s  高 宽 
def compound_video(save_location, save_name, images_list, second, width, height, fps=24):
    # 计算每张要流入的个数
    size = (width, height)                                  # (width, height) 数值可根据需要进行调整
    fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')     # 编码为 mp4v 格式
    video = cv2.VideoWriter(save_location + "/" + save_name + ".mp4", fourcc, fps, size, isColor=True)
    num = int(second * fps)
    for img in tqdm(images_list):
        for i in range(num):
            video.write(img)     # 将图像写入视频

    video.release()

# 解析命令行参数
parser = argparse.ArgumentParser(description='Tvideo')
parser.add_argument('time', type=float, help='float time')
args = parser.parse_args()

image_second = args.time   # 每一帧的时间
print(image_second)

# 读图像
print("reading images ...")
files = read_images_name(folder_path)
images = read_images(folder_path, files)
print("images num = ", len(images))

# 写入到视频
if len(images) > 0:
    row, col, chn = images[0].shape
    compound_video(save_path, save_name, images, image_second, col, row)
    
else:
    print("error no image")

